package Tree;

/**
 * @BelongsProject: SeniorArchitect-LeetCode
 * @BelongsPackage: Tree
 * @Author: zhuangxiaoyan
 * @CreateTime: 2023-10-24  22:47
 * @Description: TODO
 * @Version: 1.0
 */
public class 二叉树翻转226 {

    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return root;
        }
        // 交换左右子树
        TreeNode tmp = root.right;
        root.right = root.left;
        root.left = tmp;
        // 递归的调用左右子树
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }

    public TreeNode invertTree2(TreeNode root) {
        if (root == null) {
            return root;
        }
        // 递归左右的遍历
        invertTree(root.left);
        invertTree(root.right);
        // 中遍历
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        return root;
    }

    public TreeNode invertTree3(TreeNode root) {
        if (root == null) {
            return root;
        }
        // 递归左右的遍历
        invertTree3(root.left);
        // 中遍历
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        invertTree3(root.left); // 注意 这里依然要遍历左孩子，因为中间节点已经翻转了
        return root;
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }


}
